import Axios from "axios"
import url from './path'
import api from './api'
import qs from 'qs';
import { Message, Loading } from 'element-ui';

const axios = Axios.create({
    baseURL: url.baseURL,
    timeout: 1000
})

let loadingInstance ;
// 请求方法容器
const http = {}

for(let key in api){
    http[key] = async (params={}) => {
        let config = {
            data: {},           // 请求数据
            config: {},         // 配置参数
        }

        // 合并
        Object.assign(config, params)
        // 请求方法
        let method = api[key].method
        // 请求接口
        let url = api[key].url; 
        // 新建新的请求参数
        let newData = {};    
        
        //判断请求头类型，Conter-type isFormData===true 为上传文件
        if(config.data && config.isFormData){
            newData = new FormData();
            for(let i in config.data){
                newData.append(i,params[i]);            
            }            
        }else{
            newData = config.data
        }

        let response = {};  //请求返回值
        //判断请求方式
        if(method === 'post' || method === 'put' || method === 'patch') {
            try{
                response = await axios[method](url, newData, config)
            }catch(err){
                response = err
            }
        }else{
            try{
                response = await axios[method](url, config)
            }catch(err){
                response = err
            }
        }
        return response;    //返回请求响应值
    }
}

// 添加请求拦截器
axios.interceptors.request.use(config => {
    //发起请求前要做什么
    loadingInstance = Loading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.8)'
    })
    if(config.method === 'post' && config.headers['Content-Type'] != 'multipart/form-data') {       //除文件上传以外。防止post请求验证
        config.data = qs.stringify(config.data);
        return config
    }
    return config
}, (err) => {
    loadingInstance.close();
    Message({
        message: '请求错误，请稍后重试！',
        type: 'error',
        duration:1000
    })
    console.log(err)
})

// 添加响应拦截器
axios.interceptors.response.use(res => {
    loadingInstance.close();
    if(res.data.code === 200){
        Message({
            message: res.data.msg,
            type: 'success',
            duration:1000
        });
        return res.data.data
    }else{
        loadingInstance.close();
        Message({
            message: res.data.msg,
            type: 'error',
            duration:1000
        });
    }
}, () => {
    loadingInstance.close();
    Message({
        message: '服务器错误',
        type: 'error',
        duration:1000
    });
    return false;
})

export default http;